package ch.fusun.baron.core.command;

import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.Platform;

/**
 * Utility to administer {@link GameCommand}s.
 */
public class CommandUtil {
	private static CommandUtil instance;
	private final LinkedList<Class<?>> classes;

	private CommandUtil() {
		IConfigurationElement[] config = Platform.getExtensionRegistry()
				.getConfigurationElementsFor("ch.fusun.baron.command"); //$NON-NLS-1$
		classes = new LinkedList<Class<?>>();
		try {
			for (IConfigurationElement e : config) {
				GameCommand bean = (GameCommand) e
						.createExecutableExtension("class"); //$NON-NLS-1$
				classes.add(bean.getClass());
			}
		} catch (CoreException ex) {
			System.err.println("Handle this error with log or so: " //$NON-NLS-1$
					+ ex.getMessage());
		}
		Collections.sort(classes, new Comparator<Class<?>>() {

			@Override
			public int compare(Class<?> arg0, Class<?> arg1) {
				return arg0.toString().compareTo(arg1.toString());
			}
		});
	}

	/**
	 * @return The singleton
	 */
	public static CommandUtil getInstance() {
		if (instance == null) {
			instance = new CommandUtil();
		}
		return instance;
	}

	/**
	 * @return all the registered commands
	 */
	public LinkedList<Class<?>> getCommandClasses() {
		return classes;
	}
}
